package com.edgclub.edg.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.android.volley.VolleyError;
import com.edgclub.edg.R;
import com.edgclub.edg.api.ApiConfig;
import com.edgclub.edg.api.ResultCode;
import com.edgclub.edg.api.UserApi;
import com.edgclub.edg.api.param.UserParam;
import com.edgclub.edg.event.BroadCastEvent;
import com.edgclub.edg.event.EventBus;
import com.edgclub.edg.http.VolleyListener;
import com.edgclub.edg.model.User;
import com.edgclub.edg.utils.util.JSONHelper;
import com.edgclub.edg.utils.util.StringUtils;
import com.edgclub.edg.utils.util.UserPrefUtils;
import com.squareup.otto.ThreadEnforcer;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;
public class GzBindPhomeActivity extends GzBaseTooolBarActivity implements
		OnClickListener,VolleyListener {

	private EditText phoneNum;
	private EditText authcode;

	private Button getAuthCode;

	private UserApi userApi;

	// 用户信息
	private User user;

	private UserPrefUtils userPrefUtil;

	private String modifyCode;

	// 计时器
	private int time = 120;
	private Timer timer;
	private TimerTask timerTask;

	private String urls= ApiConfig.found_near_url;
	private String uanum="";


	private  String frompage=""; //"hongbao"


	@Override
	public int getContentView() {
		return R.layout.activity_gz_phonebind;
	}

	@Override
	public void setTitleBarView() {
		frompage=getIntent().getStringExtra("frompage");
		setCustomActionBar();
		title.setText("绑定手机");
		right_layout.setVisibility(View.VISIBLE);
		right_text.setText("确定");
		right_layout.setOnClickListener(this);
	}

	@Override
	public void initView() {
		phoneNum = (EditText) findViewById(R.id.phonenum);
		getAuthCode = (Button) findViewById(R.id.getauthcode);
		authcode = (EditText) findViewById(R.id.authcode);
		userApi = new UserApi(this);
		userPrefUtil = new UserPrefUtils(this);

		getAuthCode.setOnClickListener(this);

		if(!"".equals(getIntent().getStringExtra("url")+"")){
			urls=getIntent().getStringExtra("url")+"";
		}
		uanum=getIntent().getStringExtra("uanum")+"";
		EventBus.getEventBus(BroadCastEvent.EVENTBUS_COMMON,
				ThreadEnforcer.MAIN).register(this);
		frompage=getIntent().getStringExtra("frompage");
	}

	@Override
	public void initData() {

	}

	/**
	 * 注册方法
	 */

	private void getCode(){
		String strPhone = phoneNum.getText().toString().trim();
		if(TextUtils.isEmpty(strPhone)){
			Toast.makeText(GzBindPhomeActivity.this,"请输入你的手机号",Toast.LENGTH_SHORT).show();
			return;
		}
		if (!StringUtils.isPhoneNum(strPhone)) {
			Toast.makeText(GzBindPhomeActivity.this,"手机格式不正确",Toast.LENGTH_SHORT).show();
			return;
		}
		UserParam param = new UserParam();
		param.setUid(strPhone);
		param.setTarget("bound");
		new UserApi(this).registerGetcode(param,this);

	}


	private void register() {
		if ("".equals(phoneNum.getText().toString().trim())) {
			Toast.makeText(this, StringUtils.getString(R.string.enterphone), Toast.LENGTH_SHORT).show();
			return;
		}
		if ("".equals(authcode.getText().toString().trim())) {
			Toast.makeText(this, StringUtils.getString(R.string.enterverification), Toast.LENGTH_SHORT).show();
			return;
		}

		if (authcode.getText().toString().trim().length() != 6) {
			Toast.makeText(this, StringUtils.getString(R.string.enterverification2), Toast.LENGTH_SHORT).show();
			return;
		}

		// 拼接参数
//		UserParam param = new UserParam();
//		param.setVerifyCode(CryptUtil.md5(authcode.getText().toString().trim()));
//		// 密码必须是密文传送
//		param.setPhone(phoneNum.getText().toString().trim());
//		param.setOldPhone(userPrefUtil.getUser().getPhone());
//		param.setUserId(userPrefUtil.getUser().getId() + "");
//		// 开启注册方法
//		userApi.userBinPhone(param,this);
			String strPhone = phoneNum.getText().toString().trim();
			UserParam param = new UserParam();
			param.setUserId(userPrefUtil.getUser().getId());
			param.setPhone(strPhone);
			param.setOldPhone(userPrefUtil.getUser().getPhone()+"");
			param.setVerifyCode(authcode.getText().toString().trim());
			new UserApi(this).boundPhone(param,this);

	}

	/**
	 * 注册的监听
	 *
	 * @author 陈坤彬
	 *
	 */
	@Override
	public void onStart(String tag) {
		if (ApiConfig.APIURL.URL_BOUND_PHONE.equals(tag)) {
			showDialog(StringUtils.getString(R.string.bind), false);
		}else if(ApiConfig.APIURL.URL_REGISTER_CODE.equals(tag)){
			showDialog(StringUtils.getString(R.string.getverification), false);
		}
	}

	@Override
	public void onSuccess(String response, String tag) {
		if (ApiConfig.APIURL.URL_BOUND_PHONE.equals(tag)) {
			dismissDialog();
			if (JSONHelper.isSuccess(response)) {
				Toast.makeText(GzBindPhomeActivity.this, StringUtils.getString(R.string.bindsuccess),
						Toast.LENGTH_LONG).show();

				User user = userPrefUtil.getUser();
				user.setPhone(phoneNum.getText().toString().trim());
				userPrefUtil.saveUser(user);
				if ("hongbao".equals(frompage)) {
					Intent intent = new Intent(GzBindPhomeActivity.this,
							GzPayPassForgetActivity.class);
					intent.putExtra("frompage", "setpass");
					startActivity(intent);
				} else if("youzanfragment".equals(frompage)){
					Intent intent3=new Intent(GzBindPhomeActivity.this,GzMainActivity.class);
					setResult(RESULT_OK, intent3);
				}else {
//					Intent intent = new Intent(GzBindPhomeActivity.this,
//							YouZanWebActivity.class);
//					intent.putExtra("url", urls);
//					intent.putExtra("uanum", uanum);
//					startActivity(intent);
				}
				finish();

			} else if (JSONHelper.getResultCode(response) == 1003) {
				showToast(StringUtils.getString(R.string.verificationerror));
			} else {
				showToast(JSONHelper.getResultMsg(response) + "");
			}
		}else if (ApiConfig.APIURL.URL_REGISTER_CODE.equals(tag)){
			dismissDialog();

			if (JSONHelper.isSuccess(response)) {
				Toast.makeText(GzBindPhomeActivity.this, StringUtils.getString(R.string.checkverification),
						Toast.LENGTH_LONG).show();

				getAuthCode.setEnabled(false);
				startTimer();
				JSONObject jsonObject;
				try {
					jsonObject = new JSONObject(response);
					if (jsonObject.has("data")) {
						modifyCode = jsonObject.optString("data");
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}

			} else if (JSONHelper.getResultCode(response) == 1010) {
				Toast.makeText(GzBindPhomeActivity.this,
						"该手机已绑定其他EDG俱乐部帐号", Toast.LENGTH_LONG).show();

			} else {

				Toast.makeText(
						GzBindPhomeActivity.this,
						StringUtils.getString(R.string.verificationfail) + ":code(" + JSONHelper.getResultCode(response)
								+ ")", Toast.LENGTH_LONG).show();
			}

		}
	}

	@Override
	public void onFaile(VolleyError volleyError, String tag) {
		if (ApiConfig.APIURL.URL_BOUND_PHONE.equals(tag)) {
			dismissDialog();
			ResultCode.toastVolleyError(GzBindPhomeActivity.this,
					volleyError);
		}else if(ApiConfig.APIURL.URL_REGISTER_CODE.equals(tag)){
			dismissDialog();
			ResultCode.toastVolleyError(GzBindPhomeActivity.this,
					volleyError);

		}
		ResultCode.toastVolleyError(this, volleyError);
	}





	@Override
	protected void onDestroy() {
		// 关闭注册的线程方法
		super.onDestroy();
		EventBus.getEventBus(BroadCastEvent.EVENTBUS_COMMON,
				ThreadEnforcer.MAIN).unregister(this);

	}

	@Override
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.getauthcode:
			if (!StringUtils.isPhoneNum(phoneNum.getText().toString().trim())) {
				Toast.makeText(this, StringUtils.getString(R.string.enterrightphone), Toast.LENGTH_LONG).show();
				return;
			}
			getCode();
			break;

		default:
			break;
		case R.id.right_layout:
			register();
			closeKeyboard();
			break;
		}


	}


	private void closeKeyboard() {
		InputMethodManager inputmanger = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		inputmanger.hideSoftInputFromWindow(phoneNum.getWindowToken(), 0);
	}

	class CountDownTimerTask extends TimerTask {

		@Override
		public void run() {
			handler.sendEmptyMessage(0);
		}
	}

	private void startTimer() {
		getAuthCode.setBackgroundResource(R.drawable.register_selector);
		getAuthCode.setTextColor(getResources().getColor(R.color.c5));
		time = 60;
		if (null == timer) {
			timer = new Timer();
		}

		timerTask = new CountDownTimerTask();
		timer.schedule(timerTask, Calendar.getInstance().getTime(), 1000);
	}

	private void stopTimer() {
		getAuthCode.setBackgroundResource(R.drawable.shape_gz_get_code_bg);
		getAuthCode.setTextColor(getResources().getColor(R.color.c10));
		if (null != timer) {
			timer.cancel();
			timer = null;
		}

		if (null != timerTask) {
			timerTask.cancel();
		}

	}

	Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {

			switch (msg.what) {
			case 0:
				time--;
				getAuthCode.setText(time + StringUtils.getString(R.string.sresend));
				if (time == 0) {
					stopTimer();
					time = 120;
					getAuthCode.setEnabled(true);
					getAuthCode.setText(StringUtils.getString(R.string.sendverification));
				}
				break;

			default:
				break;
			}
			super.handleMessage(msg);
		}

	};

}
